package com.example.dao.impl;

import com.example.dao.TripDao;
import com.example.model.Trip;
import com.example.utils.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import sun.tools.java.Identifier;

import java.util.List;

public class TripDaoImpl implements TripDao {

    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    public Trip findTripById(String id) {
        String sql = "select * from trip where id = ?";
        List<Trip> trips = template.query(sql, new BeanPropertyRowMapper<Trip>(Trip.class),id);
        if (trips.size() == 0) {
            return null;
        }
        return trips.get(0);
    }
    @Override
    public boolean addTrip(Trip trip) {

        String sql = "insert into trip (id , start , end , start_time , end_time , price , count )values (? , ? , ? , ? , ? , ?  ,  ?)";
        int update = template.update(sql,
                trip.getId(),
                trip.getStart(),
                trip.getEnd(),
                trip.getStart_time(),
                trip.getEnd_time(),
                trip.getCount(),
                trip.getPrice());
        if (update <= 0) {
            return false;
        }
        return true;

    }

    @Override
    public List<Trip> findAll() {
        String sql = "select * from trip";
        List<Trip> trips = template.query(sql, new BeanPropertyRowMapper<Trip>(Trip.class));
        return trips;
    }

    @Override
    public int updateCount(String id) {
        String sql = "update trip set count = count - 1 where id = ?";
        int row = template.update(sql, id);
        return row;
    }


    @Override
    public int updateCount(String id, int count) {
        String sql = "update trip set count = (count + ?) where id = ?";
        int row = template.update(sql,count, id);
        return row;
    }
}



